package com.flame.core.utils.cipher;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Sm3Cipher
 *
 * @author wuxintong
 * @since 2023/1/28
 */
public class Sm3Cipher implements FlameCipher {

    private static final char[] HEX_CHARS =
        new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    @Override
    public String encrypt(String data) throws Exception {
        byte[] digest = MessageDigest.getInstance("SM3").digest(data.getBytes(StandardCharsets.UTF_8));
        return new String(encodeHex(digest));
    }

    private char[] encodeHex(byte[] bytes) {
        char[] chars = new char[32];

        for (int i = 0; i < chars.length; i += 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHARS[b >>> 4 & 15];
            chars[i + 1] = HEX_CHARS[b & 15];
        }

        return chars;
    }
}
